package com.bawei.lib_storage.database

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

object DBUtils {
    lateinit var db:AppDataBase

    fun init(context: Context, dbName:String){
        val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 创建评论点赞表
                database.execSQL("""
                    CREATE TABLE IF NOT EXISTS `comment_like` (
                        `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                        `comment_id` INTEGER NOT NULL,
                        `user_id` INTEGER NOT NULL,
                        `is_liked` INTEGER NOT NULL DEFAULT 1,
                        `create_time` INTEGER NOT NULL
                    )
                """)
                
                // 创建历史记录表
                database.execSQL("""
                    CREATE TABLE IF NOT EXISTS `b_history_video` (
                        `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                        `videoId` INTEGER NOT NULL,
                        `title` TEXT NOT NULL,
                        `description` TEXT NOT NULL,
                        `coverUrl` TEXT NOT NULL,
                        `videoUrl` TEXT NOT NULL,
                        `userId` TEXT NOT NULL,
                        `watchTime` INTEGER NOT NULL,
                        `watchDuration` INTEGER NOT NULL
                    )
                """)
            }
        }

        db = Room.databaseBuilder(context,AppDataBase::class.java, dbName)
//            .openHelperFactory(SupportFactory(SQLiteDatabase.getBytes("123456".toCharArray())))
            .addMigrations(MIGRATION_1_2)
            .build()
    }

    fun getDB():AppDataBase{
        if (!::db.isInitialized){
            throw NullPointerException("请先初始化数据库")
        }
        return db
    }
}